package com.cho.core.db.util;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cho.core.util.StringUtils;
import com.cho.core.vo.TableVo;

public class DBUtils {
	public static void resultSetAutoSetting(ResultSet rs, List<Map<String, String>> result) throws SQLException{
		Map<String, String> data = new HashMap<String, String>();
		
		ResultSetMetaData rsm = rs.getMetaData();
		int columnCount = rsm.getColumnCount();
		
		for (int i = 0; i < columnCount; i++) {
			String columnLabel = rsm.getColumnLabel(i+1);
			data.put(columnLabel, rs.getString(columnLabel));
		}
		
		result.add(data);
	}
	
	public static void resultSetAutoSetting(ResultSet rs, Map<String, String> result) throws SQLException{
		ResultSetMetaData rsm = rs.getMetaData();
		int columnCount = rsm.getColumnCount();
		
		for (int i = 0; i < columnCount; i++) {
			String columnLabel = rsm.getColumnLabel(i+1);
			result.put(columnLabel, rs.getString(columnLabel));
		}
	}
	
	public static String arrayToInlistIteratorFormat(String[] args){
		if(args != null){
			return Arrays.toString(args)
					.replace("[", "'")
					.replace("]", "'")
					.replaceAll(",", "','")
					.replaceAll(" ", "");
		}else{
			return "";
		}
	}
	
	public static String arrayToInlistIteratorFormat(List<String> args){
		if(args != null){
			return Arrays.toString(args.toArray())
					.replace("[", "'")
					.replace("]", "'")
					.replaceAll(",", "','")
					.replaceAll(" ", "");
		}else{
			return "";
		}
	}
	
	public static String tableSearchCondisionForTableVo(String sql, TableVo talbeVo){
		String searchCondision = "";
		
		if(talbeVo.getCrudTypes() != null && talbeVo.getCrudTypes().size() > 0){
			searchCondision += " AND B.CRUD_TYPE IN ({1})".replace("{1}", DBUtils.arrayToInlistIteratorFormat(talbeVo.getCrudTypes()));
		}
		
		if(StringUtils.isNotEmpty(talbeVo.getCrudType())){
			searchCondision += " AND B.CRUD_TYPE = '{1}'".replace("{1}", talbeVo.getCrudType());
		}
		
		if(StringUtils.isNotEmpty(talbeVo.getTableName())){
			searchCondision += " AND B.TABLE_NAME LIKE '%{1}%' ".replace("{1}", talbeVo.getTableName());
		}
		
		if(StringUtils.isNotEmpty(talbeVo.getTableFullName())){
			searchCondision += " AND B.TABLE_NAME = '{1}' ".replace("{1}", talbeVo.getTableFullName());
		}
		
		if(StringUtils.isNotEmpty(talbeVo.getFileSeq())){
			searchCondision += " AND B.FILE_SEQ = '{1}' ".replace("{1}", talbeVo.getFileSeq());
			sql = sql.replace("$DYNAMIC_ORDER_BY$", "B.FILE_SEQ, ");
		}else if(StringUtils.isNotEmpty(talbeVo.getOrderBy())){
			sql = sql.replace("$DYNAMIC_ORDER_BY$", talbeVo.getOrderBy());
		}else{
			sql = sql.replace("$DYNAMIC_ORDER_BY$", "");
		}
		
		return sql.replace("$DYNAMIC_SEARCH_CONDISION$", searchCondision);
	}
}
